package com.jacen.aws.util;

import java.io.*;

/**
 * 版权声明：Copyright(c) 2018 All Rights Reserved.
 *
 * @Author Jacen (295117485@qq.com)
 * @Date 2018/10/13 8:38
 * @Version 1.0
 * @Description 文件工具类
 */
public class FileUtil {


    /**
     * 覆盖写入文件
     *
     * @param fileNamePath 文件路径
     * @param content      内容
     */
    public static void coverWrite(String fileNamePath, String content) {
        File file = new File(fileNamePath);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(content.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 追加文件：使用FileWriter
     *
     * @param fileName
     * @param content
     */
    public static void append(String fileName, String content) {
        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName, true), "UTF-8"));
            writer.write(content);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 读取文本文件.
     */
    public static String readTxtFile(String path) {
        BufferedReader bufread;
        String read;
        FileReader fileread;
        StringBuffer readStr = new StringBuffer("");
        File filename = new File(path);
        try {
            fileread = new FileReader(filename);
            bufread = new BufferedReader(fileread);
            try {
                while ((read = bufread.readLine()) != null) {
                    readStr.append(read).append("\r\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return readStr.toString();
    }


    /**
     * 删除文本中的内容
     *
     * @param path
     * @param delContent
     */
    public static void deleteFileContent(String path, String delContent) {
        // TODO: 2018/10/18 删除文件中的ip
        String content = FileUtil.readTxtFile(path);
        content = content.replace(delContent + "\r\n", "");
        FileUtil.coverWrite(path, content);
    }

}
